import { getToken } from '@/utils/auth';
import { useGlobalState } from '@/store/globalState.js';
import { Message } from 'element-ui';
export const useTitleChange = () => {
  const title = ref('新增');
  const setTitle = val => {
    title.value = val;
  };

  return [title, setTitle];
};
export const useFileUpload = (url, fileTypes) => {
  const fileUpload = ref(null);
  const fileList = ref([]);
  const fileObj = ref({});
  const uploadFileUrl = useGlobalState().globalState.serverUrl + url; // 上传文件服务器地址
  const headers = { Authorization: 'Bearer ' + getToken() };
  const handleBeforeUpload = file => {
    const fileName = file.name.split('.');
    const fileExt = fileName[fileName.length - 1];
    // 校检文件类型
    if (fileTypes.indexOf(fileExt) < 0) {
      Message.error(`文件格式不正确, 请上传${fileTypes.join('/')}格式文件!`);
      return false;
    }
    // 校检文件大小
    // if (file?.size / 1024 / 1024 > 10) {
    //   Message.error('文件大小不能超过10MB!');
    //   return false;
    // }
  };
  const handleUploadError = () => {
    Message.error('上传文件失败');
  };
  const handleExceed = () => {
    Message.error('最多只能上传1个文件');
  };
  const handleUploadSuccess = (res, file, fList) => {
    fileList.value = fList;
    if (res.code === 200) {
      fileObj.value = res.data;
    } else {
      Message.error(res.msg);
      fileUpload.value?.handleRemove(file);
    }
  };

  return [
    fileUpload,
    fileList,
    fileObj,
    uploadFileUrl,
    headers,
    handleBeforeUpload,
    handleUploadError,
    handleExceed,
    handleUploadSuccess,
  ];
};
